import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { User, CreateUserRequest, UpdateUserRequest } from "@/types/user";
import type { Role } from "@/types/role";
import { userApi } from "@/apis/user";
import { roleApi } from "@/apis/role";

export const useUserStore = defineStore("user", () => {
  // State
  const users = ref<User[]>([]);
  const roles = ref<Role[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);
  const currentUser = ref<User | null>(null);
  const userDetail = ref<User | null>(null);

  // Getters
  const userCount = computed(() => users.value.length);

  // Actions
  const fetchUsers = async (params?: {
    page?: number;
    pageSize?: number;
    search?: string;
    gender?: number;
    roleId?: number;
  }) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await userApi.getUsers(params);
      users.value = response.data.list;
      return {
        data: response.data.list,
        total: response.data.total,
        page: response.data.page,
        pageSize: response.data.pageSize,
        totalPages: response.data.totalPages,
      }; // 返回适配后的分页信息
    } catch (err) {
      error.value = err instanceof Error ? err.message : "获取用户列表失败";
      console.error("Failed to fetch users:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const createUser = async (userData: CreateUserRequest) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await userApi.createUser(userData);
      users.value.push(response.data);
      return response.data;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "创建用户失败";
      console.error("Failed to create user:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const updateUser = async (id: number, userData: UpdateUserRequest) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await userApi.updateUser(id.toString(), userData);
      const index = users.value.findIndex((user) => user.id === id);
      if (index !== -1) {
        users.value[index] = response.data;
      }
      return response.data;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "更新用户失败";
      console.error("Failed to update user:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const deleteUser = async (id: number) => {
    loading.value = true;
    error.value = null;
    try {
      await userApi.deleteUser(id.toString());
      users.value = users.value.filter((user) => user.id !== id);
    } catch (err) {
      error.value = err instanceof Error ? err.message : "删除用户失败";
      console.error("Failed to delete user:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const clearError = () => {
    error.value = null;
  };

  const getUserDetail = async (id: number) => {
    loading.value = true;
    error.value = null;
    try {
      const response = await userApi.getUser(id.toString());
      userDetail.value = response.data;
      return response.data;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "获取用户详情失败";
      console.error("Failed to get user detail:", err);
      throw err;
    } finally {
      setTimeout(() => (loading.value = false), 500);
    }
  };

  const setCurrentUser = (user: User | null) => {
    currentUser.value = user;
  };

  const clearUserDetail = () => {
    userDetail.value = null;
  };

  const fetchRoles = async () => {
    try {
      const response = await roleApi.getRoles();
      roles.value = response.data;
      return response.data;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "获取角色列表失败";
      console.error("Failed to fetch roles:", err);
      throw err;
    }
  };

  return {
    // State
    users,
    roles,
    loading,
    error,
    currentUser,
    userDetail,
    // Getters
    userCount,
    // Actions
    fetchUsers,
    fetchRoles,
    createUser,
    updateUser,
    deleteUser,
    getUserDetail,
    clearError,
    setCurrentUser,
    clearUserDetail,
  };
});
